package com.leetcode.code;

import java.util.HashMap;
import java.util.Stack;

/**
 * 已发
 */
public class LeetCode0020Java {
    public static void main(String[] args) {
        Solution solution = new Solution();
        System.out.println("结果：" + solution.isValid("["));
    }

    private static class Solution {
        public boolean isValid(String s) {
            Stack<Character> brackets = new Stack();

            HashMap<Character, Character> bracketHashMap = new HashMap();
            bracketHashMap.put('(', ')');
            bracketHashMap.put('[', ']');
            bracketHashMap.put('{', '}');

            for (int index = 0; index < s.length(); index++) {
                if (bracketHashMap.containsKey(s.charAt(index))) { //如果是左边的括号就压入栈中
                    brackets.push(s.charAt(index));
                } else if (bracketHashMap.containsValue(s.charAt(index))) {
                    if (brackets.isEmpty()) return false;

                    Character chars = brackets.pop();

                    if (chars == null || bracketHashMap.get(chars) == null || bracketHashMap.get(chars) != s.charAt(
                            index)) {
                        return false;
                    }
                }
            }

            return brackets.isEmpty();
        }
    }
}
